package com.drama.api.task;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.auth.credentials.Credential;
import com.aliyun.auth.credentials.provider.StaticCredentialProvider;
import com.aliyun.sdk.service.mts20140618.AsyncClient;
import com.aliyun.sdk.service.mts20140618.models.*;
import com.drama.api.base.RedisUtils;
import com.drama.api.company.video.dao.CompanyVideoDao;
import com.drama.api.company.video.domain.po.CompanyVideoPO;
import com.google.gson.Gson;
import darabonba.core.client.ClientOverrideConfiguration;
import lombok.SneakyThrows;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.List;
import java.util.concurrent.CompletableFuture;

@Log4j2
public class CompanyVideoThread extends Thread {

    private CompanyVideoDao companyVideoDao;
    private RedisUtils redisUtils;

    public CompanyVideoThread(CompanyVideoDao companyVideoDao, RedisUtils redisUtils){
        this.companyVideoDao=companyVideoDao;
        this.redisUtils=redisUtils;

    }

    @SneakyThrows
    @Override
    public void run() {
        Example example=new Example(CompanyVideoPO.class);
        example.and().andEqualTo("isLabel",3);
        List<CompanyVideoPO> companyVideoPOList=companyVideoDao.selectByExample(example);
        for (CompanyVideoPO companyVideoPO:companyVideoPOList){

            if(!redisUtils.hasKey("label_jop"+companyVideoPO.getId())){
                redisUtils.delete("label_jop"+companyVideoPO.getId());
                companyVideoPO.setIsLabel(4);
                companyVideoDao.updateByPrimaryKeySelective(companyVideoPO);
                continue;
            }

            String jopId=redisUtils.get("label_jop"+companyVideoPO.getId())+"";
//            String jopId=redisUtils.getString("label_jop"+companyVideoPO.getId());
            log.info("label_jop::::::::::"+jopId);
            String labelDesc= vide_label(jopId);
            log.info(":::::::::::::::::::::::::::"+labelDesc);
            if(StringUtils.isNotBlank(labelDesc)){
                if(labelDesc.equals("fail")){
                    companyVideoPO.setIsLabel(4);
                    companyVideoDao.updateByPrimaryKeySelective(companyVideoPO);
                }else{
                    companyVideoPO.setIsLabel(1);
                    companyVideoPO.setLabelDesc(labelDesc);
                    companyVideoDao.updateByPrimaryKeySelective(companyVideoPO);
                }
                redisUtils.delete("label_jop"+companyVideoPO.getId());
            }
        }

//
//        example=new Example(CompanyVideoPO.class);
//        example.and().andEqualTo("isExamine",3);
//        List<CompanyVideoPO> companyVideoPOList1=companyVideoDao.selectByExample(example);
//        for (CompanyVideoPO companyVideoPO:companyVideoPOList1){
////            log.info("examine_jop::::::::::"+redisUtils.get("examine_jop"+companyVideoPO.getId())+"");
//            if(!redisUtils.hasKey("examine_jop"+companyVideoPO.getId())){
//                redisUtils.delete("examine_jop"+companyVideoPO.getId());
//                companyVideoPO.setIsExamine(4);
//                companyVideoDao.updateByPrimaryKeySelective(companyVideoPO);
//                continue;
//            }
////            String jopId=redisUtils.getString("examine_jop"+companyVideoPO.getId());
//            String jopId=redisUtils.get("examine_jop"+companyVideoPO.getId())+"";
//            log.info("examine_jop::::::::::"+jopId);
//            String labelDesc= vide_examine(jopId);
//            log.info(":::::::::::::::::::::::::::"+labelDesc);
//            if(StringUtils.isNotBlank(labelDesc)){
//                if(labelDesc.equals("fail")){
//                    companyVideoPO.setIsExamine(4);
//                    companyVideoDao.updateByPrimaryKeySelective(companyVideoPO);
//                }else{
//                    companyVideoPO.setIsExamine(1);
//                    companyVideoPO.setExamineDesc(labelDesc);
//                    companyVideoDao.updateByPrimaryKeySelective(companyVideoPO);
//                }
//                redisUtils.delete("examine_jop"+companyVideoPO.getId());
//            }
//        }
//



//        example=new Example(CompanyVideoPO.class);
//        example.and().andEqualTo("isCropping",3);
//        List<CompanyVideoPO> companyVideoPOList2=companyVideoDao.selectByExample(example);
//        for (CompanyVideoPO companyVideoPO:companyVideoPOList2){
////            log.info("examine_jop::::::::::"+redisUtils.get("examine_jop"+companyVideoPO.getId())+"");
//            if(!redisUtils.hasKey("cropping_jop"+companyVideoPO.getId())){
//                redisUtils.delete("cropping_jop"+companyVideoPO.getId());
//                companyVideoPO.setIsExamine(4);
//                companyVideoDao.updateByPrimaryKeySelective(companyVideoPO);
//                continue;
//            }
////            String jopId=redisUtils.getString("examine_jop"+companyVideoPO.getId());
//            String jopId=redisUtils.get("cropping_jop"+companyVideoPO.getId())+"";
//            log.info("cropping_jop::::::::::"+jopId);
//            String labelDesc= video_cropping(jopId);
//            log.info(":::::::::::::::::::::::::::"+labelDesc);
//            if(StringUtils.isNotBlank(labelDesc)){
//                if(labelDesc.equals("fail")){
//                    companyVideoPO.setIsCropping(4);
//                    companyVideoDao.updateByPrimaryKeySelective(companyVideoPO);
//                }else{
//                    companyVideoPO.setIsCropping(1);
//                    companyVideoDao.updateByPrimaryKeySelective(companyVideoPO);
//                    InputStream inputStream = new URL(labelDesc).openStream();
////                    PutObjectResult putObjectResult = ObsUtils.uploadFile(inputStream,"history/"+companyVideoPO.getCompanyId(), companyVideoPO.getVideoOldUrl().substring(companyVideoPO.getVideoOldUrl().lastIndexOf("/")+1));
////                    log.info( putObjectResult.toString());
//                }
//                redisUtils.delete("cropping_jop"+companyVideoPO.getId());
//            }
//        }
    }


//
//    private static String video_cropping(String id) {
//        if(StringUtils.isBlank(id)){
//            return "fail";
//        }
//        try {
//            Credential credential = Credential.builder()
//                    .accessKeyId("LTAI5t7HSfSSA7R2ypyedBzB")
//                    .accessKeySecret("nZQFiclFvvSH9duU6py9kyFvRlfccB")
//                    .build();
//            StaticCredentialProvider provider = StaticCredentialProvider.create(credential);
//
//            AsyncClient client = AsyncClient.builder()
//                    .region("cn-beijing") // Region ID
//                    .credentialsProvider(provider)
//                    .overrideConfiguration(ClientOverrideConfiguration.create().setEndpointOverride("mts.cn-beijing.aliyuncs.com"))
//                    .build();
//            // 创建PutObjectRequest对象。
//            QueryJobListRequest queryJobListRequest = QueryJobListRequest.builder()
//                    .jobIds(id)
//                    .build();
//            // 如果需要上传时设置存储类型和访问权限，请参考以下示例代码。
//            // 上传字符串。
//            CompletableFuture<QueryJobListResponse> response = client.queryJobList(queryJobListRequest);
//            // Synchronously get the return value of the API request
//            QueryJobListResponse resp = response.get();
//            log.info(new Gson().toJson(resp));
//            if(resp.getBody().getJobList().getJob().get(0).getState().equals("TranscodeSuccess")){
//                return "https://yujuyi.oss-cn-beijing.aliyuncs.com/"+resp.getBody().getJobList().getJob().get(0).getOutput().getOutputFile().getObject();
//            }
//            if(resp.getBody().getJobList().getJob().get(0).getState().equals("TranscodeFail")){
//                return "fail";
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//
//        return "";
//    }
//
//
//
//    public static String vide_examine(String id){
//        if(StringUtils.isBlank(id)){
//            return "fail";
//        }
//        try {
//            Credential credential=Credential.builder()
//                    .accessKeyId("LTAI5t7HSfSSA7R2ypyedBzB")
//                    .accessKeySecret("nZQFiclFvvSH9duU6py9kyFvRlfccB")
//                    .build();
//            StaticCredentialProvider provider = StaticCredentialProvider.create(credential);
//
//            AsyncClient client = AsyncClient.builder()
//                    .region("cn-beijing") // Region ID
//                    .credentialsProvider(provider)
//                    .overrideConfiguration( ClientOverrideConfiguration.create() .setEndpointOverride("mts.cn-beijing.aliyuncs.com"))
//                    .build();
//            // 创建PutObjectRequest对象。
//            QueryMediaCensorJobDetailRequest submitMediaCensorJobRequest = QueryMediaCensorJobDetailRequest.builder()
//                    .jobId(id)
//                    .build();
//            // 如果需要上传时设置存储类型和访问权限，请参考以下示例代码。
//            // 上传字符串。
//            CompletableFuture<QueryMediaCensorJobDetailResponse> response = client.queryMediaCensorJobDetail(submitMediaCensorJobRequest);
//            // Synchronously get the return value of the API request
//            StringBuffer stringBuffer=new StringBuffer();
//            QueryMediaCensorJobDetailResponse resp = response.get();
//            log.info(new Gson().toJson(resp));
//            if(resp.getBody().getMediaCensorJobDetail().getState().equals("Success")){
//                stringBuffer.append("整体审核结果：");
//                if(resp.getBody().getMediaCensorJobDetail().getSuggestion().equals("block")){
//                    stringBuffer.append("有违规");
//                }
//                if(resp.getBody().getMediaCensorJobDetail().getSuggestion().equals("review")){
//                    stringBuffer.append("疑似违规");
//                }
//                if(resp.getBody().getMediaCensorJobDetail().getSuggestion().equals("pass")){
//                    stringBuffer.append("无违规");
//                }
//                stringBuffer.append("|");
////                if(resp.getBody().getMediaCensorJobDetail().getVensorCensorResult().getCensorResults().get())
//                System.out.println("====");
//                System.out.println(resp.getBody().getMediaCensorJobDetail().getVensorCensorResult().getVideoTimelines().getVideoTimeline().size());
//                for (int i=0;i<resp.getBody().getMediaCensorJobDetail().getVensorCensorResult().getVideoTimelines().getVideoTimeline().size();i++){
//                    for (int j=0;j< resp.getBody().getMediaCensorJobDetail().getVensorCensorResult().getVideoTimelines().getVideoTimeline().get(i).getCensorResults().getCensorResult().size();j++){
//                        if(resp.getBody().getMediaCensorJobDetail().getVensorCensorResult().getVideoTimelines().getVideoTimeline().get(i).getCensorResults().getCensorResult().get(j).getSuggestion().equals("block")){
//                            stringBuffer.append( "https://yujuyi.oss-cn-beijing.aliyuncs.com/"+resp.getBody().getMediaCensorJobDetail().getVensorCensorResult().getVideoTimelines().getVideoTimeline().get(i).getObject());
//                            stringBuffer.append(",");
//                        }
//                    }
//                }
//                System.out.println(stringBuffer.toString().substring(0,stringBuffer.length()-1));
//                return stringBuffer.toString().substring(0,stringBuffer.length()-1);
//            }
//            if(resp.getBody().getMediaCensorJobDetail().getState().equals("Fail")){
//                return "fail";
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return "";
//    }

    public static String vide_label(String id) {
        if(StringUtils.isBlank(id)){
            return "fail";
        }
        try {
            Credential credential = Credential.builder()
                    .accessKeyId("LTAI5t7HSfSSA7R2ypyedBzB")
                    .accessKeySecret("nZQFiclFvvSH9duU6py9kyFvRlfccB")
                    .build();
            StaticCredentialProvider provider = StaticCredentialProvider.create(credential);

            AsyncClient client = AsyncClient.builder()
                    .region("cn-beijing") // Region ID
                    .credentialsProvider(provider)
                    .overrideConfiguration(ClientOverrideConfiguration.create().setEndpointOverride("mts.cn-beijing.aliyuncs.com"))
                    .build();
            // 创建PutObjectRequest对象。
            QuerySmarttagJobRequest querySmarttagJobRequest = QuerySmarttagJobRequest.builder()
                    .jobId(id)
                    .build();
            // 如果需要上传时设置存储类型和访问权限，请参考以下示例代码。
            // 上传字符串。
            CompletableFuture<QuerySmarttagJobResponse> response = client.querySmarttagJob(querySmarttagJobRequest);
            // Synchronously get the return value of the API request
            QuerySmarttagJobResponse resp = response.get();
            log.info(new Gson().toJson(resp));
            if(resp.getBody().getJobStatus().equals("Success")){
                StringBuffer stringBuffer=new StringBuffer();
                String data="";
                if(resp.getBody().getResults().getResult().get(1).getType().equals("TextLabel")){
                    data=  resp.getBody().getResults().getResult().get(1).getData();
                }
                if(resp.getBody().getResults().getResult().get(0).getType().equals("TextLabel")){
                    data= resp.getBody().getResults().getResult().get(0).getData();
                }
                if(StringUtils.isNotBlank(data)){
                    JSONObject dataJSon=JSONObject.parseObject(data);
                    if(dataJSon.containsKey("tags")){
                        JSONArray jsonArray=dataJSon.getJSONArray("tags");
                        for (int i=0;i<jsonArray.size();i++){
                            JSONObject one=jsonArray.getJSONObject(i);
                            stringBuffer.append( one.getString("name")).append("：").append( one.getString("value")).append("|");
                        }
                    }
                }
                if(stringBuffer==null||stringBuffer.length()<1){
                    return "未识别出有效信息";
                }
                System.out.println(stringBuffer.toString().substring(0,stringBuffer.length()-1));
               return stringBuffer.toString().substring(0,stringBuffer.length()-1);
            }
            if(resp.getBody().getJobStatus().equals("Fail")){
                return "fail";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

}
